//
//  YWNetworkManager.swift
//  demo02
//
//  Created by 陈友文 on 2021/1/22.
//

import UIKit
import AFNetworking

let kTimeoutInterval:TimeInterval = 15000
#if DEBUG

//let BASE_URL:String = "http://asay.vaiwan.com/api"
let BASE_URL:String = "http://aisai.mercs.xyz:8897/api/"
#else
let BASE_URL:String = "http://aisai.mercs.xyz:8897/api/"
#endif
class YWNetworkManager: AFHTTPSessionManager {

    enum YWNetworkType {
        case get
        case post
        case put
        case delete
    }
    
    static let sharedManager:YWNetworkManager = {
        
        let instence = YWNetworkManager(baseURL: URL(string: BASE_URL), sessionConfiguration: URLSessionConfiguration.default)
        
        instence.requestSerializer = AFJSONRequestSerializer()
        instence.requestSerializer.timeoutInterval = kTimeoutInterval
        instence.responseSerializer = AFJSONResponseSerializer()
        instence.responseSerializer.acceptableContentTypes =  NSSet(objects: "application/json", "text/json", "text/javascript", "text/html", "text/xml", "text/plain","application/x-www-form-urlencoded") as? Set<String>

        return instence
    }()

    
    /// 加载普通请求
    /// - Parameters:
    ///   - type: 请求类型
    ///   - url: url
    ///   - params: 参数
    ///   - headers: 请求头
    ///   - completion: 回调
    func yw_loadNetworkData(type:YWNetworkType,
                            url:String,
                            params:Any?,
                            headers:[String:String]?,
                            completion:@escaping (Any?,Bool)->Void
    ){
        DPrint("params\(params)")
        DPrint("token Bearer \(UserDefaults.standard.value(forKey: "token") ?? "")")
        
        var headers = headers
        if headers == nil {
            headers = ["Authorization":"Bearer \(UserDefaults.standard.value(forKey: "token") ?? "")"]
        }
        else {
            headers!["Authorization"] = "Bearer \(UserDefaults.standard.value(forKey: "token") ?? "")"
        }
        let successTask = {(task:URLSessionDataTask,json:Any?)->() in
            print("url:\(url)  successTask:\(json!)")
            guard let res = json as? [String:Any],
                  let code = res["code"] as? Int,
                  let msg = res["msg"] as? String
            else{
                completion(nil,false)
                return
            }
            if code == 200 {
                completion(res,true)
            }else{
                if code == 402 || code == 403{
                    YWProgressHUD.showAisaiMsg(message: "登陆失效，请重新登陆")
                    UserDefaults.standard.set("", forKey: "token")
                    UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: false)
                    UIApplication.shared.keyWindow?.rootViewController = LoginViewController()
                }
                else{
                    YWProgressHUD.showAisaiMsg(message: msg)
                    completion(res,false)
                }
            }

        }
        let failureTask = {(task:URLSessionDataTask?,error:Error)-> () in
            print("网络请求失败:\(error)")
            YWProgressHUD.showAisaiMsg(message: "网络请求失败\((error as NSError).code)")
            completion(nil,false)
        }
        if type == .get {
            self.get(url, parameters: params, headers: headers, progress: nil, success: successTask, failure: failureTask)
            
        } else if type == .post{
            self.post(url, parameters: params, headers: headers, progress: nil, success: successTask, failure: failureTask)
            
        }else if type == .put{
            self.put(url, parameters: params, headers: headers, success: successTask, failure: failureTask)
            
        }else if type == .delete{
            self.delete(url, parameters: params, headers: headers, success: successTask, failure: failureTask)
            
        }
    }
    
    /// 加载普通请求
    /// - Parameters:
    ///   - type: 请求类型
    ///   - url: url
    ///   - params: 参数
    ///   - headers: 请求头
    ///   - completion: 回调
    func yw_loadNetworkDataLoadding(type:YWNetworkType,
                            url:String,
                            params:Any?,
                            headers:[String:String]?,
                            completion:@escaping (Any?,Bool)->Void
    ){
        SVProgressHUD.show()
        DPrint("params\(params)")
        DPrint("token Bearer \(UserDefaults.standard.value(forKey: "token") ?? "")")
        var headers = headers
        if headers == nil {
            headers = ["Authorization":"Bearer \(UserDefaults.standard.value(forKey: "token") ?? "")"]
        }
        else {
            headers!["Authorization"] = "Bearer \(UserDefaults.standard.value(forKey: "token") ?? "")"
        }
        let successTask = {(task:URLSessionDataTask,json:Any?)->() in
            SVProgressHUD.dismiss()
            print("url:\(url)  successTask:\(json!)")
            guard let res = json as? [String:Any],
                  let code = res["code"] as? Int,
                  let msg = res["msg"] as? String
            else{
                completion(nil,false)
                return
            }
//            completion(res,true)
            if code == 200 {
                completion(res,true)
            }else{
                if code == 402 || code == 403{
                    YWProgressHUD.showAisaiMsg(message: "登陆失效，请重新登陆")
                    UserDefaults.standard.set("", forKey: "token")
                    UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: false)
                    UIApplication.shared.keyWindow?.rootViewController = LoginViewController()
                }
                else{
                    YWProgressHUD.showAisaiMsg(message: msg)
                    completion(res,false)
                }
            }
        }
        let failureTask = {(task:URLSessionDataTask?,error:Error)-> () in
            SVProgressHUD.dismiss()
            YWProgressHUD.showAisaiMsg(message: "网络请求失败\((error as NSError).code)")
            print("网络请求失败:\(error)")
            completion(nil,false)
        }
        if type == .get {
            self.get(url, parameters: params, headers: headers, progress: nil, success: successTask, failure: failureTask)
            
        } else if type == .post{
            self.post(url, parameters: params, headers: headers, progress: nil, success: successTask, failure: failureTask)
            
        }else if type == .put{
            self.put(url, parameters: params, headers: headers, success: successTask, failure: failureTask)
            
        }else if type == .delete{
            self.delete(url, parameters: params, headers: headers, success: successTask, failure: failureTask)
            
        }
    }
    
    
    /// 上传图片
    /// - Parameters:
    ///   - url: url
    ///   - params: 参数
    ///   - imgs: 图片数组
    ///   - headers: 请求头
    ///   - completion: 回调
    func yw_uploadImg(url:String,
                   params:Any?,
                   imgs:[UIImage],
                   headers:[String:String]?,
                   completion:@escaping (Any?,Bool)->Void){
        var headers = headers
        if headers == nil {
            headers = ["Authorization":"Bearer \(UserDefaults.standard.value(forKey: "token") ?? "")"]
        }
        else {
            headers!["Authorization"] = "Bearer \(UserDefaults.standard.value(forKey: "token") ?? "")"
        }
        let successTask = {(task:URLSessionDataTask,json:Any?)->() in
            print("url:\(url)  successTask:\(json!)")
            guard let res = json as? [String:Any],
                  let code = res["code"] as? Int,
                  let msg = res["msg"] as? String
            else{
                completion(nil,false)
                return
            }
            if code == 200 {
                completion(res,true)
            }else{
                if code == 402 || code == 403{
                    YWProgressHUD.showAisaiMsg(message: "登陆失效，请重新登陆")
                    UserDefaults.standard.set("", forKey: "token")
                    UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: false)
                    UIApplication.shared.keyWindow?.rootViewController = LoginViewController()
                }
                else{
                    YWProgressHUD.showAisaiMsg(message: msg)
                    completion(res,false)
                }
            }
        }
        let failureTask = {(task:URLSessionDataTask?,error:Error)-> () in
            print("网络请求失败:\(error)")
            YWProgressHUD.showAisaiMsg(message: "网络请求失败\((error as NSError).code)")
            completion(nil,false)
        }
        self.post(url, parameters: params, headers: headers, constructingBodyWith: { (formData) in
            for i in 0 ..< imgs.count{
                if let imgData = imgs[i].jpegData(compressionQuality: 0.3){
                    formData.appendPart(withFileData: imgData, name: "file", fileName: "image\(i).jpg", mimeType: "image/jpg")
                }
            }
            
        }, progress: nil, success: successTask, failure: failureTask)
    }
    
    
    /// 上传视屏
    /// - Parameters:
    ///   - url: url
    ///   - params: 参数
    ///   - imgs: 图片数组
    ///   - headers: 请求头
    ///   - completion: 回调
    func yw_uploadVideo(url:String,
                   params:Any?,
                   videoUrl:String?,
                   headers:[String:String]?,
                   progress:@escaping (Progress)->Void,
                   completion:@escaping (Any?,Bool)->Void){
        var headers = headers
        if headers == nil {
            headers = ["Authorization":"Bearer \(UserDefaults.standard.value(forKey: "token") ?? "")"]
        }
        else {
            headers!["Authorization"] = "Bearer \(UserDefaults.standard.value(forKey: "token") ?? "")"
        }
        let successTask = {(task:URLSessionDataTask,json:Any?)->() in
            print("url:\(url)  successTask:\(json!)")
            guard let res = json as? [String:Any],
                  let code = res["code"] as? Int,
                  let msg = res["msg"] as? String
            else{
                completion(nil,false)
                return
            }
            if code == 200 {
                completion(res,true)
            }else{
                if code == 402 || code == 403{
                    YWProgressHUD.showAisaiMsg(message: "登陆失效，请重新登陆")
                    UserDefaults.standard.set("", forKey: "token")
                    UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: false)
                    UIApplication.shared.keyWindow?.rootViewController = LoginViewController()
                }
                else{
                    YWProgressHUD.showAisaiMsg(message: msg)
                    completion(res,false)
                }
            }
        }
        let failureTask = {(task:URLSessionDataTask?,error:Error)-> () in
            print("网络请求失败:\(error)")
            YWProgressHUD.showAisaiMsg(message: "网络请求失败\((error as NSError).code)")
            completion(nil,false)
        }
        
        let progressTask = {(task:Progress) ->() in
            progress(task)
        }
        
        self.post(url, parameters: params, headers: headers, constructingBodyWith: { (formData) in
            
            formData.appendPart(withFileData: NSData(contentsOfFile: videoUrl ?? "")! as Data, name: "file", fileName: "123456.mp4", mimeType: "video/mp4")
        }, progress: progressTask, success: successTask, failure: failureTask)}
    
    
}
